package com.core.cloudbusiness.sheet.mayor.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.cloudbusiness.sheet.mayor.mapper.CloudSheetMayorMapper;
import com.core.cloudbusiness.sheet.mayor.service.CloudSheetMayorService;
import com.core.cloudbusiness.sheet.process.service.CloudSheetProcessService;
import com.core.cloudbusiness.system.depart.service.CloudSystemDepartService;
import com.core.cloudbusiness.tool.CommonRequestContext;
import com.core.cloudcommon.CommonCustomException;
import com.core.cloudcommon.CommonInteger;
import com.core.cloudcommon.CommonPageResponse;
import com.core.cloudcommon.CommonRandomExample;
import com.core.cloundbusinessapi.sheet.mayor.dto.CloudSheetMayorDTO;
import com.core.cloundbusinessapi.sheet.mayor.dto.CloudSheetQueryDTO;
import com.core.cloundbusinessapi.sheet.mayor.enums.CloudSheetMayorResultCode;
import com.core.cloundbusinessapi.sheet.mayor.enums.CloudSheetMayorStatusEnums;
import com.core.cloundbusinessapi.sheet.mayor.vo.CloudSheetMayorImportVO;
import com.core.cloundbusinessapi.sheet.mayor.vo.CloudSheetQueryListVO;
import com.core.cloundbusinessapi.sheet.mayor.vo.CloudSheetQueryVO;
import com.core.cloundbusinessapi.sheet.mayor.vo.CloudSheetTearVO;
import com.core.cloundbusinessapi.sheet.process.dto.CloudSheetProcessDTO;
import com.core.cloundbusinessapi.sheet.process.enums.CloudSheetProcessStateEnums;
import com.core.cloundbusinessapi.sheet.process.vo.CloudSheetProcessVO;
import com.core.cloundbusinessapi.sheet.process.vo.CloudSheetQueryProcessListVO;
import com.core.cloundbusinessapi.system.depart.dto.CloudSystemDepartQueryDTO;
import com.core.cloundbusinessapi.system.depart.vo.CloudSystemDepartVO;
import com.core.cloundbusinessapi.system.user.dto.CloudSystemUserDTO;
import com.github.javafaker.Faker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author =====Lqj=====
 * @className CloudSheetMayorServiceImpl
 * @description
 * @create 2024/11/19 17:13
 **/
@Slf4j
@Service
public class CloudSheetMayorServiceImpl implements CloudSheetMayorService {

    @Autowired
    private CloudSheetMayorMapper cloudSheetMayorMapper;

    @Autowired
    private CloudSheetProcessService cloudSheetProcessService;


    @Autowired
    private CloudSystemDepartService cloudSystemDepartService;

    final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

    final DateTimeFormatter formatterTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private Snowflake snowflake = IdUtil.createSnowflake(1L, 1L);

    final String type = "01";


    @Override
    public String importSheet(CloudSheetMayorImportVO cloudSheetMayorVO) {
        if (Objects.isNull(cloudSheetMayorVO)) {
            throw new CommonCustomException(CloudSheetMayorResultCode.CODE500001.getCode(), CloudSheetMayorResultCode.CODE500001.getMsg());
        }
        log.info("系统导入工单请求参数：" + JSON.toJSONString(cloudSheetMayorVO));
        Faker faker = new Faker(Locale.CHINA);
        CloudSheetMayorDTO cloudSheetMayorDTO = new CloudSheetMayorDTO();
        BeanUtils.copyProperties(cloudSheetMayorVO, cloudSheetMayorDTO);
        Long nextId = snowflake.nextId();
        String id = LocalDate.now().format(formatter) + nextId;
        cloudSheetMayorDTO.setId(nextId);
        cloudSheetMayorDTO.setSheetCode(type + id);
        cloudSheetMayorDTO.setSheetMatter(CommonRandomExample.appoint(1, 30));
        cloudSheetMayorDTO.setSheetEmergency(CommonRandomExample.appoint(1, 3));
        cloudSheetMayorDTO.setSheetAcceptanceType(CommonRandomExample.appoint(1, 3));
        List<Integer> list = Arrays.asList(1001, 2001, 3001);
        Collections.shuffle(list);
        cloudSheetMayorDTO.setSheetType(list.get(CommonInteger.Integer0));
        cloudSheetMayorDTO.setSheetSecrecy(CommonRandomExample.appoint(1, 2));
        cloudSheetMayorDTO.setSheetSource(CommonInteger.Integer1);
        DateTime futureDate = DateUtil.offsetDay(DateUtil.date(), CommonInteger.Integer5);
        cloudSheetMayorDTO.setSheetDeadline(futureDate.toDateStr());
        cloudSheetMayorDTO.setSheetReturnDeadline(DateUtil.offsetDay(DateUtil.date(), CommonInteger.Integer3).toDateStr());
        cloudSheetMayorDTO.setSheetStatus(CloudSheetMayorStatusEnums.PROPOSED.getMsg());
        cloudSheetMayorDTO.setCitizenName(faker.name().fullName());
        cloudSheetMayorDTO.setCitizenSex(CommonRandomExample.appoint(1, 2));
        cloudSheetMayorDTO.setCitizenPhone(faker.phoneNumber().cellPhone());
        cloudSheetMayorDTO.setCitizenNumber(CommonRandomExample.generateIDCard());
        cloudSheetMayorDTO.setCitizenContactPhone(faker.phoneNumber().cellPhone());
        cloudSheetMayorDTO.setIncidentArea(faker.address().fullAddress());
        cloudSheetMayorDTO.setSheetLandmark(faker.address().fullAddress());
        cloudSheetMayorDTO.setBusNumber(CommonRandomExample.generateLicensePlate());
        cloudSheetMayorDTO.setSheetDependency(faker.address().fullAddress());
        cloudSheetMayorDTO.setSheetAddress(faker.address().fullAddress());
        cloudSheetMayorDTO.setCreateTime(new Date());
        //获取当前登陆的用户信息
        CloudSystemUserDTO user = CommonRequestContext.getCurrentUser();
        cloudSheetMayorDTO.setCreateBy(user.getUserName());
        cloudSheetMayorMapper.insert(cloudSheetMayorDTO);
        CloudSheetProcessVO cloudSheetProcessVO = new CloudSheetProcessVO();
        cloudSheetProcessVO.setSheetCode(cloudSheetMayorDTO.getSheetCode());
        cloudSheetProcessVO.setSheetProcessState(CloudSheetProcessStateEnums.TYPE10.getState());
        cloudSheetProcessVO.setHandleUnit(user.getDepartId().toString());
        cloudSheetProcessVO.setHandleOpinion("系统导入工单初始化");
        cloudSheetProcessVO.setReplyOpinion("系统导入工单初始化");
        cloudSheetProcessService.task(cloudSheetProcessVO);
        return cloudSheetMayorDTO.getSheetCode();
    }

    @Override
    public CommonPageResponse querySheet(CloudSheetQueryVO cloudSheetQueryVO) {
        if (Objects.isNull(cloudSheetQueryVO)) {
            throw new CommonCustomException(CloudSheetMayorResultCode.CODE500002.getCode(), CloudSheetMayorResultCode.CODE500002.getMsg());
        }
        log.info("分页查询工单请求参数：" + JSON.toJSONString(cloudSheetQueryVO));
        CommonPageResponse commonPageResponse = new CommonPageResponse();
        String sheetCode = cloudSheetQueryVO.getSheetCode();
        CloudSystemUserDTO user = CommonRequestContext.getCurrentUser();
        Page page = new Page(cloudSheetQueryVO.getPageNumber(), cloudSheetQueryVO.getPageSize());
        if ("01".equals(user.getOrgCode())) {
            IPage<CloudSheetMayorDTO> cloudSheetMayorDTOIPage = cloudSheetMayorMapper.queryMayorMapper(page, sheetCode, null);
            commonPageResponse.setCurrent(cloudSheetMayorDTOIPage.getCurrent());
            commonPageResponse.setSize(cloudSheetMayorDTOIPage.getSize());
            commonPageResponse.setTotal(cloudSheetMayorDTOIPage.getTotal());
            commonPageResponse.setData(cloudSheetMayorDTOIPage.getRecords());
            return commonPageResponse;
        }

        IPage<CloudSheetMayorDTO> cloudSheetMayorDTOIPage = cloudSheetMayorMapper.queryMayorMapper(page, sheetCode, user.getDepartId().toString());
        commonPageResponse.setCurrent(cloudSheetMayorDTOIPage.getCurrent());
        commonPageResponse.setSize(cloudSheetMayorDTOIPage.getSize());
        commonPageResponse.setTotal(cloudSheetMayorDTOIPage.getTotal());
        commonPageResponse.setData(cloudSheetMayorDTOIPage.getRecords());
        return commonPageResponse;

    }


    @Override
    public String tearSheet(CloudSheetTearVO cloudSheetTearVO) {
        if (cloudSheetTearVO.getSheetCode() == null || cloudSheetTearVO.getHandleUnit() == null) {
            throw new CommonCustomException(CloudSheetMayorResultCode.CODE500003.getCode(), CloudSheetMayorResultCode.CODE500003.getMsg());
        }
        log.info("拆分工单请求参数：" + JSON.toJSONString(cloudSheetTearVO));
        IPage<CloudSheetMayorDTO> cloudSheetMayorDTOIPage = cloudSheetMayorMapper.queryMayorMapper(null, cloudSheetTearVO.getSheetCode(), null);
        CloudSheetMayorDTO cloudSheetMayorDTO = cloudSheetMayorDTOIPage.getRecords().get(CommonInteger.Integer1);
        Long nextId = snowflake.nextId();
        String id = LocalDate.now().format(formatter) + nextId;
        cloudSheetMayorDTO.setId(nextId);
        cloudSheetMayorDTO.setSuperiorSheetCode(cloudSheetTearVO.getSheetCode());
        cloudSheetMayorDTO.setSheetCode(type + id);
        CloudSystemDepartVO cloudSystemDepartVO = new CloudSystemDepartVO();
        cloudSystemDepartVO.setDepartName(cloudSheetTearVO.getHandleUnit());
        List<CloudSystemDepartQueryDTO> query = cloudSystemDepartService.query(cloudSystemDepartVO);
        if (query.isEmpty()) {
            throw new CommonCustomException(CloudSheetMayorResultCode.CODE500004.getCode(), CloudSheetMayorResultCode.CODE500004.getMsg());
        }
        CloudSystemDepartQueryDTO cloudSystemDepartQueryDTO = query.get(CommonInteger.Integer0);
        cloudSheetMayorDTO.setHandleUnit(String.valueOf(cloudSystemDepartQueryDTO.getId()));
        cloudSheetMayorDTO.setCreateTime(new Date());
        cloudSheetMayorMapper.insert(cloudSheetMayorDTO);
        CloudSheetProcessVO cloudSheetProcessVO = new CloudSheetProcessVO();
        cloudSheetProcessVO.setSheetCode(cloudSheetMayorDTO.getSheetCode());
        cloudSheetProcessVO.setSheetProcessState(CloudSheetProcessStateEnums.TYPE12.getState());
        cloudSheetProcessVO.setHandleUnit(cloudSheetTearVO.getHandleUnit());
        cloudSheetProcessVO.setHandleOpinion("该单为拆分单，请及时处理");
        cloudSheetProcessVO.setReplyOpinion("该单为拆分单，请及时处理");
        cloudSheetProcessService.task(cloudSheetProcessVO);
        return cloudSheetMayorDTO.getSheetCode();
    }

    @Override
    public void updateSheetStatus(String sheetCode, String type, String handleUnit) {
        Page page = new Page();
        IPage<CloudSheetMayorDTO> cloudSheetMayorDTOIPage = cloudSheetMayorMapper.queryMayorMapper(page, sheetCode, null);
        CloudSheetMayorDTO cloudSheetMayorDTO = cloudSheetMayorDTOIPage.getRecords().get(CommonInteger.Integer0);
        if (CloudSheetProcessStateEnums.TYPE13.getState().equals(type) &&
                !CloudSheetMayorStatusEnums.HANDLE.getMsg().equals(cloudSheetMayorDTO.getSheetStatus())) {
            cloudSheetMayorMapper.updateSheetStatusMapper(sheetCode, CloudSheetMayorStatusEnums.HANDLE.getMsg(), handleUnit);
        }
    }

    @Override
    public List<CloudSheetMayorDTO> querySheetList(CloudSheetQueryListVO cloudSheetQueryListVO) {
        log.info("拉取工单接口请求参数：" + JSON.toJSONString(cloudSheetQueryListVO));
        LocalDateTime startTime = LocalDateTime.parse(cloudSheetQueryListVO.getStartTime(), formatterTime);
        LocalDateTime stopTime = LocalDateTime.parse(cloudSheetQueryListVO.getStopTime(), formatterTime);
        Duration duration = Duration.between(startTime, stopTime);
        if (duration.toHours() > 48) {
            throw new CommonCustomException(CloudSheetMayorResultCode.CODE500006.getCode(), CloudSheetMayorResultCode.CODE500006.getMsg());
        }
        CloudSystemUserDTO user = CommonRequestContext.getCurrentUser();
        if ("01".equals(user.getOrgCode())) {
            List<CloudSheetMayorDTO> cloudSheetMayorDTOS = cloudSheetMayorMapper.queryMayorListMapper(cloudSheetQueryListVO.getStartTime(), cloudSheetQueryListVO.getStopTime(), null);
            return cloudSheetMayorDTOS;
        }
        List<CloudSheetMayorDTO> cloudSheetMayorDTOS = cloudSheetMayorMapper.queryMayorListMapper(cloudSheetQueryListVO.getStartTime(), cloudSheetQueryListVO.getStopTime(), String.valueOf(user.getDepartId()));

        return cloudSheetMayorDTOS;
    }
}
